/**
  ******************************************************************************
  * File Name          : networktsl.c
  * Description        : This file provides code for the configuration
  *                      of the edp app instances.
  ******************************************************************************
  * @attention
  ******************************************************************************
  */
#include "bsp.h"
#include "tskcfg.h"
#include "core_mqtt.h"

#define NETWORK_STREAM_BUFFER_MAXLEN       8192

StreamBufferHandle_t NetWork_StreamBuffer_sbhd = NULL;
static StaticStreamBuffer_t network_stream_buffer_strc;
static uint8_t network_stream_buffer[NETWORK_STREAM_BUFFER_MAXLEN];

static int32_t network_send(NetworkContext_t * pContext, const void * pBuffer, size_t bytes);
static int32_t network_recv(NetworkContext_t * pContext, void * pBuffer, size_t bytes);

const TransportInterface_t Network_TransportInterface = {
	.pNetworkContext = NULL,
	.send = network_send,
	.recv = network_recv,
};

static int32_t network_send(NetworkContext_t * pContext, const void * pBuffer, size_t bytes)
{
	size_t i;
  const uint8_t *buf;
	
	LED_MQTT_Data(LED_ON);
	
	buf = (const uint8_t *)pBuffer;
	
	for(i=0; i<bytes; i++)
	{
    USART_DATA(USART1) = (buf[i]& (uint16_t)0x01FFU);
    while(!(USART_STAT0(USART1) & USART_STAT0_TBE));
	}
	
	LED_MQTT_Data(LED_OFF);
	
	return bytes;
}

static int32_t network_recv(NetworkContext_t * pContext, void * pBuffer, size_t bytes)
{
	return xStreamBufferReceive(NetWork_StreamBuffer_sbhd, ( void * )pBuffer, bytes, 1000);
}

uint32_t Network_GetTimestamp(void)
{
	return xTaskGetTickCount();
}

void Network_TransportLayerInit(void)
{
  NetWork_StreamBuffer_sbhd = xStreamBufferCreateStatic(sizeof(network_stream_buffer), \
																												 1, \
	                                                       network_stream_buffer, \
	                                                       &network_stream_buffer_strc);
  xStreamBufferReset(NetWork_StreamBuffer_sbhd);
}

void MQTT_ResetRecvBuffer(void)
{
	xStreamBufferReset(NetWork_StreamBuffer_sbhd);
}

void Network_ReceiveISR(uint8_t dat)
{
	LED_MQTT_Data(LED_ON);
	
	if(NetWork_StreamBuffer_sbhd != NULL)
	{
		xStreamBufferSendFromISR(NetWork_StreamBuffer_sbhd, &dat, 1, NULL);
	}
	
	LED_MQTT_Data(LED_OFF);
}
